package net.pws.oos.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;

import net.pws.common.security.filter.ClientVersion;
import net.pws.common.security.filter.ClientVersionProvider;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.ServletContextAware;

public class AndroidVersionProvider implements ClientVersionProvider,
		ServletContextAware {

	private final transient Log logger = LogFactory.getLog(AndroidVersionProvider.class);

	private DefaultClientVersion version = new DefaultClientVersion();

	private boolean autoRefresh = true;

	private long lastModified = -1;

	private ServletContext context;

	public boolean isAutoRefresh() {
		return autoRefresh;
	}

	public void setAutoRefresh(boolean autoRefresh) {
		this.autoRefresh = autoRefresh;
	}

	public ClientVersion getVersion() {
		loadVersionProperties();
		return version;
	}

	public void setServletContext(ServletContext arg0) {
		this.context = arg0;
	}

	private void loadVersionProperties() {
		String androidPath = context.getRealPath("/android");
		File configFile = new File(androidPath, "version.properties");
		if (!configFile.exists()) {
			throw new RuntimeException("The version information not found!");
		}

		if (configFile.lastModified() > lastModified) {
			lastModified = configFile.lastModified();
			InputStream is = null;
			try {
				is = new FileInputStream(configFile);
				Properties properties = new Properties();
				properties.load(is);
				String minVersion = properties.getProperty("minVersion", "1");
				String curVersion = properties.getProperty("version", "1");
				String path = properties.getProperty("path");
				String updateLog = properties.getProperty("updateLog");
				version.setMinVersion(Integer.parseInt(minVersion));
				version.setVersion(Integer.parseInt(curVersion));
				version.setPath(path);
				version.setUpdateLog(updateLog);
			} catch (Exception e) {
				logger.error(e, e);
				throw new RuntimeException("Read version information failed!");
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (Exception e) {
					}
				}
			}
		}
	}
}
